package com.wrx.club_management_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wrx.club_management_backend.common.AjaxResult;
import com.wrx.club_management_backend.dto.VenueBookingItem;
import com.wrx.club_management_backend.entity.ClubActivity;
import com.wrx.club_management_backend.entity.Venue;
import com.wrx.club_management_backend.mapper.ClubActivityMapper;
import com.wrx.club_management_backend.mapper.VenueMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/venue")
public class VenueController {

    @Autowired
    private VenueMapper venueMapper;

    /**
     * 查询所有场地
     */
    @GetMapping("/list")
    public AjaxResult list() {
        List<Venue> venues = venueMapper.selectList(null);
        return AjaxResult.success(venues);
    }

    /**
     * 分页查询场地
     */
    @GetMapping("/page")
    public AjaxResult page(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String name) {

        Page<Venue> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Venue> queryWrapper = new QueryWrapper<>();

        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }

        Page<Venue> resultPage = venueMapper.selectPage(page, queryWrapper);
        return AjaxResult.success(resultPage);
    }

    /**
     * 根据ID查询场地
     */
    @GetMapping("/{id}")
    public AjaxResult getById(@PathVariable Long id) {
        Venue venue = venueMapper.selectById(id);
        if (venue == null) {
            return AjaxResult.error("场地不存在");
        }
        return AjaxResult.success(venue);
    }

    /**
     * 添加场地
     */
    @PostMapping
    public AjaxResult add(@RequestBody Venue venue) {
        System.out.println(venue);
        int result = venueMapper.insert(venue);
        if (result > 0) {
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    /**
     * 更新场地
     */
    @PutMapping
    public AjaxResult update(@RequestBody Venue venue) {
        if (venue.getId() == null) {
            return AjaxResult.error("ID不能为空");
        }

        int result = venueMapper.updateById(venue);
        if (result > 0) {
            return AjaxResult.success("更新成功");
        }
        return AjaxResult.error("更新失败，场地可能不存在");
    }

    /**
     * 删除场地
     */
    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        int result = venueMapper.deleteById(id);
        if (result > 0) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败，场地可能不存在");
    }

    /**
     * 批量删除场地
     */
    @DeleteMapping("/batch")
    public AjaxResult batchDelete(@RequestBody List<Long> ids) {
        int result = venueMapper.deleteBatchIds(ids);
        if (result > 0) {
            return AjaxResult.success("批量删除成功，共删除" + result + "条数据");
        }
        return AjaxResult.error("批量删除失败");
    }


    /**
     * 查询可用场地
     */
    @GetMapping("/available")
    public AjaxResult availableVenues(
            @RequestParam String beginTime,
            @RequestParam Long duration) {

        if (beginTime == null || duration == null) {
            return AjaxResult.error("参数不完整");
        }

        // 获取所有场地
        List<Venue> allVenues = venueMapper.selectList(null);

        // 过滤出可用场地
        List<Venue> availableVenues = allVenues.stream()
                .filter(venue -> venueMapper.checkVenueAvailability(venue.getId(), beginTime, duration) == 0)
                .collect(Collectors.toList());

        return AjaxResult.success(availableVenues);
    }

    /**
     * 检查场地在指定时间段是否可用
     */
    @GetMapping("/check-availability")
    public AjaxResult checkAvailability(
            @RequestParam Long venueId,
            @RequestParam String beginTime,
            @RequestParam Long duration) {

        if (venueId == null || beginTime == null || duration == null) {
            return AjaxResult.error("参数不完整");
        }

        // 检查场地是否存在
        Venue venue = venueMapper.selectById(venueId);
        if (venue == null) {
            return AjaxResult.error("场地不存在");
        }

        // 检查场地在指定时间段是否已被预约
        int conflictCount = venueMapper.checkVenueAvailability(venueId, beginTime, duration);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("available", conflictCount == 0);
        resultMap.put("conflictCount", conflictCount);

        return AjaxResult.success("查询成功", resultMap);
    }

    @Autowired
    ClubActivityMapper clubActivityMapper;

    @PostMapping("/bookingList/{venueId}")
    public AjaxResult bookingList(@PathVariable("venueId") Long venueId){
        //1. 先获取所有的占用情况
        Venue venue = venueMapper.selectById(venueId);
        List<VenueBookingItem> list = venueMapper.bookingList(venue.getId());
        for (VenueBookingItem venueBookingItem : list) {
            Long activityId = venueBookingItem.getActivityId();
            ClubActivity clubActivity = clubActivityMapper.selectById(activityId);
            venueBookingItem.setActivity(clubActivity);
        }
        return AjaxResult.success(list);
    }
}